<template>
  <div class="app-container">
    

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      />
      <el-table-column
        label="商品名称"
        prop="product_name"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="期望价格"
        prop="expected_price"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <span>¥{{ scope.row.expected_price }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="商品描述"
        prop="description"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        label="联系方式"
        prop="contact"
        align="center"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="商品图片"
        prop="images"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.images && scope.row.images.length > 0" class="image-preview">
            <el-image
              :src="scope.row.images[0]"
              :preview-src-list="scope.row.images"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px;"
            />
            <div v-if="scope.row.images.length > 1" class="image-count">
              +{{ scope.row.images.length - 1 }}
            </div>
          </div>
          <span v-else class="no-image">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="created_at"
        align="center"
        width="180"
        sortable
      />
      
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      @pagination="getList"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '添加期望商品' : '编辑期望商品'"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 100%;"
      >
        <el-form-item label="商品名称" prop="product_name">
          <el-input v-model="temp.product_name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="期望价格" prop="expected_price">
          <el-input-number
            v-model="temp.expected_price"
            :precision="2"
            :min="0"
            placeholder="请输入期望价格"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="temp.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="temp.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :limit="5"
            list-type="picture-card"
            action="/api/upload"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogImageVisible" title="图片预览">
      <img :src="dialogImageUrl" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createItem, updateItem, deleteItem } from '@/api/shopping'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: 'QiwangList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 10
      },
      temp: {
        id: undefined,
        product_name: '',
        expected_price: 0,
        description: '',
        contact: '',
        images: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        product_name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
        expected_price: [{ required: true, message: '期望价格不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '商品描述不能为空', trigger: 'blur' }],
        contact: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }]
      },
      fileList: [],
      dialogImageVisible: false,
      dialogImageUrl: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async  getList() {
      this.listLoading = true
      const res = await fetchList(this.listQuery)

    

      setTimeout(() => {
        this.list = res.data.data
        this.total =  res.data.total
        this.listLoading = false
      }, 1000)

    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.fileList = row.images ? row.images.map((url, index) => ({
        name: `image${index + 1}`,
        url: url
      })) : []
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        const index = this.list.findIndex(item => item.id === row.id)
        if (index > -1) {
          this.list.splice(index, 1)
          this.total--
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        
        // 实际API调用代码
        // deleteItem(row.id).then(() => {
        //   this.$message({
        //     type: 'success',
        //     message: '删除成功!'
        //   })
        //   this.getList()
        // })
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.images = this.fileList.map(file => file.url || file.response.url)
          tempData.id = Date.now() // 临时ID
          tempData.created_at = new Date().toISOString().slice(0, 19).replace('T', ' ')
          this.list.unshift(tempData)
          this.total++
          this.dialogFormVisible = false
          this.$message({
            message: '创建成功',
            type: 'success'
          })
          
          // 实际API调用代码
          // createItem(tempData).then(() => {
          //   this.getList()
          //   this.dialogFormVisible = false
          //   this.$message({
          //     message: '创建成功',
          //     type: 'success'
          //   })
          // })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.images = this.fileList.map(file => file.url || file.response.url)
          const index = this.list.findIndex(item => item.id === tempData.id)
          if (index > -1) {
            this.list.splice(index, 1, tempData)
          }
          this.dialogFormVisible = false
          this.$message({
            message: '更新成功',
            type: 'success'
          })
          
          // 实际API调用代码
          // updateItem(tempData.id, tempData).then(() => {
          //   this.getList()
          //   this.dialogFormVisible = false
          //   this.$message({
          //     message: '更新成功',
          //     type: 'success'
          //   })
          // })
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        product_name: '',
        expected_price: 0,
        description: '',
        contact: '',
        images: []
      }
      this.fileList = []
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleUploadSuccess(response, file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
  
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }
}

.image-preview {
  position: relative;
  display: inline-block;
  
  .image-count {
    position: absolute;
    top: -5px;
    right: -5px;
    background: #409eff;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    font-size: 12px;
  }
}

.no-image {
  color: #999;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>

